package com.weipeep.sys.controller;


import java.io.*;
import java.util.*;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.weipeep.common.base.BaseController;
import com.weipeep.common.mail.EmailService;
import com.weipeep.common.utils.poi.*;
import com.weipeep.sys.domain.WebUserDO;
import com.weipeep.sys.domain.XunJiaDO;
import com.weipeep.sys.service.WebUserService;
import com.weipeep.sys.service.XunJiaService;
import com.weipeep.sys.vo.ProductSearch;
import com.weipeep.sys.vo.ProductVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.weipeep.sys.domain.ProductDO;
import com.weipeep.sys.service.ProductService;
import com.weipeep.common.utils.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2018-04-20 22:55:14 | wangyun</small>
 */
@Controller
@RequestMapping("/sys/product")
public class ProductController extends BaseController {
	@Autowired
	private ProductService productService;
	@Autowired
	private XunJiaService xunJiaService;
	@Resource
	private EmailService emailService;
	@Autowired
	private WebUserService webUserService;
	@GetMapping()
	@RequiresPermissions("sys:product:product")
	String Product(){
	    return "sys/product/product";
	}
	
	@ResponseBody
	@GetMapping("/list")
//	@RequiresPermissions("sys:product:product")
	public Result<Page<ProductDO>> list(Integer pageNumber, Integer pageSize, ProductDO productDTO){
		// 查询列表数据
        Page<ProductDO> page = new Page<>(pageNumber, pageSize);
		productDTO.setUserId(getUserId());
		String model = productDTO.getModel();
		productDTO.setModel(null);
        Wrapper<ProductDO> wrapper = new EntityWrapper<ProductDO>(productDTO);
		if(model !=null && model.trim().length()>0) {
			wrapper.like("model", model);
		}
		wrapper.orderBy("upload_time desc");
		page = productService.selectPage(page, wrapper);
        int total = productService.selectCount(wrapper);
        page.setTotal(total);
        return Result.ok(page);
	}
	@ResponseBody
	@GetMapping("/hotsell")
//	@RequiresPermissions("sys:product:product")
	public Result<Page<ProductVo>> hotsell(Integer pageNumber, Integer pageSize, ProductDO productDTO){
		// 查询列表数据
		Page<ProductDO> page = new Page<>(pageNumber, pageSize);
		productDTO.setHotSell(1);
		String model = productDTO.getModel();
		productDTO.setModel(null);
		Wrapper<ProductDO> wrapper = new EntityWrapper<ProductDO>(productDTO);
		if(model !=null && model.trim().length()>0) {
			wrapper.like("model", model);
		}
		wrapper.orderBy("upload_time desc");
		page = productService.selectPage(page, wrapper);
		int total = productService.selectCount(wrapper);
		List<ProductDO> productDOList = page.getRecords();
		Set<Long> userIds = Sets.newConcurrentHashSet();
		Page<ProductVo> pageresult = new Page<>(pageNumber, pageSize);
		productDOList.forEach(productDO -> userIds.add(productDO.getUserId()));
		if (userIds.size()>0){
			List<ProductVo> resultList =Lists.newArrayList();
			List<WebUserDO> webUserDOList = webUserService.selectBatchIds(Lists.newArrayList(userIds));
			Map<Long,WebUserDO> map = Maps.newHashMap();
			for (WebUserDO webUserDO:webUserDOList){
				map.put(webUserDO.getId(),webUserDO);
			}
			for(ProductDO productDO:productDOList){
				ProductVo productVo = new ProductVo();
				if (map.get(productDO.getUserId())!=null){
					productVo.setCompany(map.get(productDO.getUserId()).getCompany());
					productVo.setUserAccount(map.get(productDO.getUserId()).getUserAccount());
					productVo.setMobile(map.get(productDO.getUserId()).getMobile());
					productVo.setQq(map.get(productDO.getUserId()).getQq());
					productVo.setTelephone(map.get(productDO.getUserId()).getTelephone());
				}
				productVo.setModel(productDO.getModel());
				productVo.setUserId(productDO.getUserId());
				productVo.setNumber(productDO.getNumber());
				productVo.setType(productDO.getType());
				productVo.setBrand(productDO.getBrand());
				productVo.setNote(productDO.getNote());
				productVo.setId(productDO.getId());
				productVo.setUploadTime(productDO.getUploadTime());
				productVo.setHotSell(productDO.getHotSell());
				productVo.setOpenShow(productDO.getOpenShow());
				productVo.setUnitPrice(productDO.getUnitPrice());
				resultList.add(productVo);
			}
			pageresult.setRecords(resultList);
		}
		pageresult.setTotal(total);
		return Result.ok(pageresult);
	}

	@GetMapping("/add")
	String add(){
	    return "sys/product/add";
	}

	@GetMapping("/import")
	public String toImportExcel(){
		return "sys/product/import";
	}

	@ResponseBody
	@PostMapping("/import")
	public Result doImportExcel(@RequestParam("file") MultipartFile file) throws InvalidFormatException {
		if (!file.isEmpty()) {
			if (!ExcelImportUtils.validateExcel(file.getOriginalFilename())){
				return Result.fail().setMsg("上传文件有错");
			}
			ExcelEnum excelEnum= ExcelEnum.XLS;
			if (ExcelImportUtils.isExcel2003(file.getOriginalFilename())){
				excelEnum=ExcelEnum.XLS;
			}else if (ExcelImportUtils.isExcel2007(file.getOriginalFilename())){
				excelEnum=ExcelEnum.XLSX;
			}
			try {
				// 这里只是简单例子，文件直接输出到项目路径下。
				// 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
				// 还有关于文件格式限制、文件大小限制，详见：中配置。
				InputStream in = file.getInputStream();
				List<ProductData> productDataList = null;
				try {
					productDataList = new ExcelHelper<ProductData>().readExcel(in,excelEnum,ProductData.class, new ExcelResolver<ProductData>(){
						@Override
						public boolean resolve(ProductData obj) throws Exception {
							String brand = getCellValue("品牌");
							String model = getCellValue("型号");
							String type = getCellValue("类型");
							String unitPrice = getCellValue("单价");
							String number = getCellValue("数量");
							String note = getCellValue("备注");
							if (StringUtils.isEmpty(model)){
								throw new Exception("型号不能为空");
							}
							obj.setBrand(brand);
							obj.setModel(model);
							obj.setType(type);
							obj.setUnitPrice(unitPrice);
							obj.setNumber(number);
							obj.setNote(note);
							return true;
						}
					});
				}catch (Exception e){
					return Result.fail().setMsg("导入库存失败，请检查模版格式!（"+e.getMessage()+"）");
				}
				if (productDataList.size()==0){
					return Result.fail().setMsg("内容不能为空!");
				}
				List<ProductDO> productDOList = Lists.newArrayList();
				productDataList.forEach(productData -> {
					ProductDO productDO = new ProductDO();
					productDO.setUserId(getUserId());
					productDO.setUploadTime(Calendar.getInstance().getTime());
					productDO.setBrand(productData.getBrand());
					productDO.setModel(productData.getModel());
					productDO.setNumber(productData.getNumber());
					productDO.setUnitPrice(productData.getUnitPrice());
					productDO.setType(productData.getType());
					productDO.setNote(productData.getNote());
					productDO.setOpenShow(1);
					productDO.setHotSell(0);
					productDOList.add(productDO);
				});
				if (productDOList.size()>0){
					ProductSearch productSearch = new ProductSearch();
					productSearch.setUserId(getUserId());
					int countIndb = productService.selectProductCount(productSearch);
					if (countIndb+productDataList.size()>30000){
						return Result.fail().setMsg("库存数量不能超过30000条");
					}
					productService.insertBatch(productDOList);
				}else {
					return Result.fail().setMsg("导入失败");
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return Result.fail();
			} catch (IOException e) {
				e.printStackTrace();
				return Result.fail();
			}
		}
		return Result.ok();
	}
	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id,Model model){
		ProductDO product = productService.selectById(id);
		model.addAttribute("product", product);
	    return "sys/product/edit";
	}
	@GetMapping("/xunjia/{id}")
	String xunjia(@PathVariable("id") Long id,Model model){
		ProductDO product = productService.selectById(id);
		model.addAttribute("product", product);
		return "sys/product/xunjia";
	}
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
//	@RequiresPermissions("sys:product:add")
	public Result<String> save( ProductDO product){
		product.setUserId(this.getUserId());
		product.setUploadTime(Calendar.getInstance().getTime());
		ProductSearch productSearch = new ProductSearch();
		productSearch.setUserId(getUserId());
		int countIndb = productService.selectProductCount(productSearch);
		if (countIndb>=30000){
			return Result.fail().setMsg("库存不能超过30000条");
		}
		if(product.getHotSell()==1){
			productSearch.setHotSell(1);
			countIndb = productService.selectProductCount(productSearch);
			if (countIndb>=50){
				return Result.fail().setMsg("热卖不能超过50条");
			}
		}
		if(productService.insert(product)){
			return Result.ok();
		}
		return Result.fail();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
//	@RequiresPermissions("sys:product:edit")
	public Result<String>  update( ProductDO product){
		if(product.getHotSell()==1){
			ProductSearch productSearch = new ProductSearch();
			productSearch.setUserId(getUserId());
			productSearch.setHotSell(1);
			int countIndb = productService.selectProductCount(productSearch);
			if (countIndb>=50){
				return Result.fail().setMsg("热卖不能超过50条");
			}
		}
		product.setUploadTime(Calendar.getInstance().getTime());
		productService.updateById(product);
		return Result.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
//	@RequiresPermissions("sys:product:remove")
	public Result<String>  remove( Long id){
		if(productService.deleteById(id)){
            return Result.ok();
		}
		return Result.fail();
	}
	/**
	 * 删除
	 */
	@PostMapping( "/clear")
	@ResponseBody
//	@RequiresPermissions("sys:product:remove")
	public Result<String>  clear(){
		Long userId = getUserId();
		Map<String,Object> map = Maps.newHashMap();
		map.put("user_id",userId);
		try {
			productService.deleteByMap(map);
		}catch (Exception e){
			return Result.fail().setMsg("清空失败");
		}
		return Result.ok();
	}

	@PostMapping( "/refresh")
	@ResponseBody
//	@RequiresPermissions("sys:product:remove")
	public Result<String>  refresh(){
		Long userId = getUserId();
		Map<String,Object> map = Maps.newHashMap();
		map.put("userId",userId);
		map.put("uploadTime",Calendar.getInstance().getTime());
		try {
			productService.refresh(map);
		}catch (Exception e){
			return Result.fail().setMsg("清空失败");
		}
		return Result.ok();
	}
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
//	@RequiresPermissions("sys:product:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		productService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}
	/**
	 * 批量询价
	 */
	@PostMapping( "/batchXunjia")
	@ResponseBody
//	@RequiresPermissions("sys:product:batchRemove")
	public Result<String>  batchXunjia(@RequestParam("ids[]") Long[] ids,@RequestParam("number") String number){
		List<Long> productIds = Lists.newArrayList(ids);
		List<ProductDO> productDOList = productService.selectBatchIds(productIds);
		List<XunJiaDO> xunJiaDOList = Lists.newArrayList();
		productDOList.stream().forEach(productDO -> {
			XunJiaDO xunJia = new XunJiaDO();
			xunJia.setToUserId(productDO.getUserId());
			xunJia.setUserId(getUserId());
			xunJia.setProductId(productDO.getId());
			xunJia.setCreateTime(Calendar.getInstance().getTime());
			xunJia.setNumber(number);
			xunJia.setModel(productDO.getModel());
			xunJia.setBrand(productDO.getBrand());
			xunJia.setType(productDO.getType());
			xunJia.setXunJiaType(1);//对product生成询价
			xunJiaDOList.add(xunJia);
		});
		if(xunJiaDOList.size()>0){
			if(xunJiaService.insertBatch(xunJiaDOList)) {
				for (XunJiaDO xunJia : xunJiaDOList) {
					final Long userId = xunJia.getToUserId();
					final String subject = "收到询价";
					final StringBuilder sb = new StringBuilder();
					WebUserDO webUserDO = webUserService.selectById(getUserId());
					sb.append("<html>");
					sb.append("<body>");
					sb.append("<div>您好,这是由一号轴承网www.01bearing.com接到的询价单，请即登录www.01bearing.com回复处理！祝您成功！</div>");
					sb.append("<div>以下是采购商的询价信息:</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;品牌："+(xunJia.getBrand()==null?"":xunJia.getBrand())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;类型："+(xunJia.getType()==null?"":xunJia.getType())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;型号："+(xunJia.getModel()==null?"":xunJia.getModel())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;数量："+(xunJia.getNumber()==null?"":xunJia.getNumber())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;接受价格："+(xunJia.getUnitPrice()==null?"":xunJia.getUnitPrice())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;备注："+(xunJia.getNote()==null?"":xunJia.getNote())+"</div>");
					sb.append("<div>此询价来自:</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;姓名："+(webUserDO.getUserName()==null?"":webUserDO.getUserName())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;公司名称："+(webUserDO.getCompany()==null?"":webUserDO.getCompany())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;电话："+(webUserDO.getTelephone()==null?"":webUserDO.getTelephone())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;传真："+(webUserDO.getFaxs()==null?"":webUserDO.getFaxs())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;手机："+(webUserDO.getMobile()==null?"":webUserDO.getMobile())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;Email："+(webUserDO.getEmail()==null?"":webUserDO.getEmail())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;QQ："+(webUserDO.getQq()==null?"":webUserDO.getQq())+"：</div>");
					sb.append("<div>&nbsp;&nbsp;&nbsp;&nbsp;地址："+(webUserDO.getAddress()==null?"":webUserDO.getAddress())+"：</div>");
					sb.append("<div>此信由一号轴承网www.01bearing.com专业轴承交易平台实时发送,感谢您选择我们的服务!</div>");
					sb.append("</body>");
					sb.append("</html>");
					new Thread() {
						@Override
						public void run() {
							WebUserDO userDO = webUserService.selectById(userId);
							if (userDO.getEmail() != null) {
								emailService.sendHtmlMail(userDO.getEmail(), subject, sb.toString());
							}
						}
					}.start();
				}
			}
		}
		return Result.ok().setMsg("批量询价成功");
	}
}
